#pragma execution_character_set("utf-8")
#include "module_manager.h"
#include <QQmlContext>
#include <QQuickWindow>
#include <QCoreApplication>
#include <QtQml>
#include <iostream>

// Include ViewModels and custom items
#include "viewmodels/map_view_model.h"
#include "viewmodels/dashboard_view_model.h"
#include "viewmodels/vehicle_view_model.h"
#include "viewmodels/task_view_model.h"
#include "viewmodels/simulator_view_model.h"
#include "viewmodels/log_view_model.h"
#include "custom_items/map_background_item.h"
#include "factories/viewmodel_factory.h"

// Infrastructure
#include "infrastructure/di/servicecontainer.h"
#include "infrastructure/logging/log_broadcast_sink.h"
#include "application/map/map_application_service.h"

// TODO: 等待各层服务实现后取消注释
// #include "application/scheduling/ISchedulingService.h"
// #include "application/vehicle/IVehicleService.h"
// #include "application/task/ITaskService.h"

ModuleManager::ModuleManager()
	: QObject(nullptr)
	, m_serviceContainer(nullptr)
{
}

void ModuleManager::setServiceContainer(std::shared_ptr<infrastructure::ServiceContainer> container)
{
	m_serviceContainer = container;

	// 创建ViewModelFactory
	if (m_serviceContainer) {
		m_viewModelFactory = std::make_unique<presentation::factories::ViewModelFactory>(m_serviceContainer, this);
		qDebug() << "ModuleManager: ViewModelFactory created with service container";
	}
	else {
		qWarning() << "ModuleManager: Service container is null, ViewModelFactory will not be created";
	}
}

bool ModuleManager::createAndInitialize()
{

	try {
		// QML引擎已经在头文件中定义为栈对象，无需创建

		// 1. 首先设置上下文属性（参考官方示例顺序）
		setupContextProperties();

		// 3. Register other QML types
		registerQmlTypes();

		// 4. Load QML file (following official example pattern)
		const QUrl url(QStringLiteral("qrc:/qml/main.qml"));
		m_engine.load(url);

		// 5. 检查是否成功创建根对象
		bool success = !m_engine.rootObjects().isEmpty();
		if (success) {
			// 当应用退出时清理模块
			connect(&m_engine, &QQmlApplicationEngine::quit, this, &ModuleManager::onApplicationQuit);
		}
		else {
			qCritical() << "[ModuleManager] Failed to create QML application - no root objects";
		}

		return success;

	}
	catch (const std::exception& ex) {
		qCritical() << "[ModuleManager] Exception during QML creation:" << ex.what();
		return false;
	}
	catch (...) {
		qCritical() << "[ModuleManager] Unknown exception during QML creation";
		return false;
	}
}

QQmlApplicationEngine* ModuleManager::engine()
{
	return &m_engine;  // 返回栈对象的地址
}


presentation::factories::ViewModelFactory* ModuleManager::getViewModelFactory() const
{
	return m_viewModelFactory.get();
}

void ModuleManager::registerQmlTypes()
{
	// 注册AGV系统相关的QML类型

	// 地图相关组件
	qmlRegisterType<presentation::MapViewModel>("TSCore.Presentation", 1, 0, "MapViewModel");
	qmlRegisterType<presentation::MapBackgroundItem>("TSCore.Presentation", 1, 0, "MapBackgroundItem");

	// 仪表板相关组件
	qmlRegisterType<presentation::DashboardViewModel>("TSCore.Presentation", 1, 0, "DashboardViewModel");

	// 车辆管理相关组件
	qmlRegisterType<presentation::viewmodels::VehicleViewModel>("TSCore.Presentation", 1, 0, "VehicleViewModel");
	qmlRegisterType<presentation::viewmodels::AgvListModel>("TSCore.Presentation", 1, 0, "AgvListModel");

	// 任务管理相关组件
	qmlRegisterType<presentation::viewmodels::TaskViewModel>("TSCore.Presentation", 1, 0, "TaskViewModel");
	qmlRegisterType<presentation::viewmodels::TaskListModel>("TSCore.Presentation", 1, 0, "TaskListModel");

	// 仿真管理相关组件
	qmlRegisterType<presentation::viewmodels::SimulatorViewModel>("TSCore.Presentation", 1, 0, "SimulatorViewModel");

	// 日志相关组件
	qmlRegisterType<presentation::viewmodels::LogViewModel>("TSCore.Presentation", 1, 0, "LogViewModel");
	qmlRegisterType<presentation::viewmodels::SystemLogModel>("TSCore.Presentation", 1, 0, "SystemLogModel");
	qmlRegisterType<presentation::viewmodels::LogFilterProxyModel>("TSCore.Presentation", 1, 0, "LogFilterProxyModel");


	// TODO: 等待ViewModels实现后取消注释

	// 仪表板相关
	// qmlRegisterType<DashboardViewModel>("AGV.ViewModels", 1, 0, "DashboardViewModel");

	// AGV管理相关
	// qmlRegisterType<AgvListViewModel>("AGV.ViewModels", 1, 0, "AgvListViewModel");
	// qmlRegisterType<AgvControlViewModel>("AGV.ViewModels", 1, 0, "AgvControlViewModel");

	// 任务管理相关
	// qmlRegisterType<TaskListViewModel>("AGV.ViewModels", 1, 0, "TaskListViewModel");
	// qmlRegisterType<TaskDetailViewModel>("AGV.ViewModels", 1, 0, "TaskDetailViewModel");

}

void ModuleManager::initializeQmlInterface(const QUrl& url)
{
	// 操作系统标识
	bool isWindows = false;
	bool isMacOS = false;
	bool isLinux = false;
	QString osName = "Unknown OS";

#if defined(Q_OS_WINDOWS)
	isWindows = true;
	osName = "Windows";
#elif defined(Q_OS_MACOS)
	isMacOS = true;
	osName = "macOS";
#elif defined(Q_OS_LINUX)
	isLinux = true;
	osName = "GNU/Linux";
#endif

	// Qt版本标识
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
	const bool isQt6 = true;
#else
	const bool isQt6 = false;
#endif

	// 设置上下文属性
	setupContextProperties();

	// 设置系统信息到QML上下文
	auto context = m_engine.rootContext();
	context->setContextProperty("Cpp_IsWindows", isWindows);
	context->setContextProperty("Cpp_IsMacOS", isMacOS);
	context->setContextProperty("Cpp_IsLinux", isLinux);
	context->setContextProperty("Cpp_OSName", osName);
	context->setContextProperty("Cpp_Qt6", isQt6);


	// 加载主QML文件
	m_engine.load(url);
}

void ModuleManager::onApplicationQuit()
{
	// TODO: 清理模块和服务
}

void ModuleManager::configureFonts()
{
	// 加载自定义字体资源（如果有的话）
	// TODO: 添加字体资源文件
	// QFontDatabase::addApplicationFont(":/fonts/Roboto-Regular.ttf");
	// QFontDatabase::addApplicationFont(":/fonts/Roboto-Bold.ttf");

	// 设置默认应用字体
	QFont appFont;
	appFont.setFamily("Microsoft YaHei"); // 中文友好字体
	appFont.setPointSize(10);
	//QCoreApplication::instance()->setFont(appFont);

}

void ModuleManager::setupContextProperties()
{
	auto context = m_engine.rootContext();

	// 设置系统信息到QML上下文（参考官方示例）
	bool isWindows = false;
	bool isMacOS = false;
	bool isLinux = false;
	QString osName = "Unknown OS";

#if defined(Q_OS_WINDOWS)
	isWindows = true;
	osName = "Windows";
#elif defined(Q_OS_MACOS)
	isMacOS = true;
	osName = "macOS";
#elif defined(Q_OS_LINUX)
	isLinux = true;
	osName = "GNU/Linux";
#endif

	// Qt版本标识
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
	const bool isQt6 = true;
#else
	const bool isQt6 = false;
#endif

	context->setContextProperty("Cpp_IsWindows", isWindows);
	context->setContextProperty("Cpp_IsMacOS", isMacOS);
	context->setContextProperty("Cpp_IsLinux", isLinux);
	context->setContextProperty("Cpp_OSName", osName);
	context->setContextProperty("Cpp_Qt6", isQt6);

	// 注入ViewModelFactory
	if (m_viewModelFactory) {
		context->setContextProperty("ViewModelFactory", m_viewModelFactory.get());
		qDebug() << "ModuleManager: ViewModelFactory injected to QML context";

		// 创建全局 ViewModels 并注册为上下文属性
		createGlobalViewModels(context);
	}
	else {
		qWarning() << "ModuleManager: ViewModelFactory not available";
	}

	// 如果有服务容器，解析并设置服务
	if (m_serviceContainer) {
		try {
			// 解析地图应用服务
			auto mapAppService = m_serviceContainer->resolve<application::MapApplicationService>();
			if (mapAppService) {
				context->setContextProperty("MapApplicationService", mapAppService.get());
				qDebug() << "ModuleManager: MapApplicationService injected successfully";
			}
			else {
				qWarning() << "ModuleManager: Failed to resolve MapApplicationService";
			}
		}
		catch (const std::exception& e) {
			qWarning() << "ModuleManager: Exception resolving services:" << e.what();
		}
	}

	// TODO: 等待服务实现后设置上下文属性
	// 调度管理器
	// auto schedulingService = serviceContainer->resolve<ISchedulingService>();
	// context->setContextProperty("SchedulingManager", schedulingService.get());

	// 车辆管理器
	// auto vehicleService = serviceContainer->resolve<IVehicleService>();
	// context->setContextProperty("VehicleManager", vehicleService.get());

	// 任务管理器
	// auto taskService = serviceContainer->resolve<ITaskService>();
	// context->setContextProperty("TaskManager", taskService.get());
}

void ModuleManager::createGlobalViewModels(QQmlContext* context)
{
	qDebug() << "ModuleManager: Creating global ViewModels...";

	try {
		// 创建MapViewModel
		if (!m_globalMapViewModel && m_viewModelFactory) {
			m_globalMapViewModel = m_viewModelFactory->createMapViewModel(this);
			if (m_globalMapViewModel) {
				context->setContextProperty("GlobalMapViewModel", m_globalMapViewModel);
				qDebug() << "ModuleManager: GlobalMapViewModel created and registered";
			} else {
				qWarning() << "ModuleManager: Failed to create GlobalMapViewModel";
			}
		}

		// 创建DashboardViewModel
		if (!m_globalDashboardViewModel && m_viewModelFactory) {
			m_globalDashboardViewModel = m_viewModelFactory->createDashboardViewModel(this);
			if (m_globalDashboardViewModel) {
				context->setContextProperty("GlobalDashboardViewModel", m_globalDashboardViewModel);
				qDebug() << "ModuleManager: GlobalDashboardViewModel created and registered";
			} else {
				qWarning() << "ModuleManager: Failed to create GlobalDashboardViewModel";
			}
		}

		// 创建VehicleViewModel
		if (!m_globalVehicleViewModel && m_viewModelFactory) {
			m_globalVehicleViewModel = m_viewModelFactory->createVehicleViewModel(this);
			if (m_globalVehicleViewModel) {
				context->setContextProperty("GlobalVehicleViewModel", m_globalVehicleViewModel);
				qDebug() << "ModuleManager: GlobalVehicleViewModel created and registered";
			} else {
				qWarning() << "ModuleManager: Failed to create GlobalVehicleViewModel";
			}
		}

		// 创建TaskViewModel
		if (!m_globalTaskViewModel && m_viewModelFactory) {
			m_globalTaskViewModel = m_viewModelFactory->createTaskViewModel(this);
			if (m_globalTaskViewModel) {
				context->setContextProperty("GlobalTaskViewModel", m_globalTaskViewModel);
				qDebug() << "ModuleManager: GlobalTaskViewModel created and registered";
			} else {
				qWarning() << "ModuleManager: Failed to create GlobalTaskViewModel";
			}
		}

		// 创建ResourceViewModel
		if (!m_globalResourceViewModel && m_viewModelFactory) {
			m_globalResourceViewModel = m_viewModelFactory->createResourceViewModel(this);
			if (m_globalResourceViewModel) {
				context->setContextProperty("GlobalResourceViewModel", m_globalResourceViewModel);
				qDebug() << "ModuleManager: GlobalResourceViewModel created and registered";
			} else {
				qWarning() << "ModuleManager: Failed to create GlobalResourceViewModel";
			}
		}

		// 创建SimulatorViewModel
		if (!m_globalSimulatorViewModel && m_viewModelFactory) {
			m_globalSimulatorViewModel = m_viewModelFactory->createSimulatorViewModel(this);
			if (m_globalSimulatorViewModel) {
				context->setContextProperty("GlobalSimulatorViewModel", m_globalSimulatorViewModel);
				qDebug() << "ModuleManager: GlobalSimulatorViewModel created and registered";
			} else {
				qWarning() << "ModuleManager: Failed to create GlobalSimulatorViewModel";
			}
		}

		// 创建LogViewModel
		if (!m_globalLogViewModel && m_viewModelFactory) {
			m_globalLogViewModel = m_viewModelFactory->createLogViewModel(this);
			if (m_globalLogViewModel) {
				context->setContextProperty("GlobalLogViewModel", m_globalLogViewModel);
				qDebug() << "ModuleManager: GlobalLogViewModel created and registered";

				// 安装日志广播 Sink
				infrastructure::logging::installLogBroadcastSink();
				qDebug() << "ModuleManager: Log broadcast sink installed";
			} else {
				qWarning() << "ModuleManager: Failed to create GlobalLogViewModel";
			}
		}

	} catch (const std::exception& e) {
		qWarning() << "ModuleManager: Exception creating global ViewModels:" << e.what();
	}

}

void ModuleManager::initializeResources()
{
	// 在Qt6中，静态库的资源通常会自动初始化
	// 如果需要手动初始化，可以在这里添加 Q_INIT_RESOURCE 调用
}
